package io.persimmon.core.util;

import io.persimmon.core.util.bo.CollectionDiffResult;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectionUtil {

    public static <K, T> Map<K, T> toMap(Collection<T> list, Function<T, K> func) {
        return list.stream()
                .collect(Collectors.toMap(func, t -> t));
    }

    public static <K, T> Map<K, T> toMap(K k, T t) {
        Map<K, T> map = new HashMap<>();
        map.put(k, t);
        return map;
    }

    public static <T> CollectionDiffResult<T> diff(Collection<T> newList, Collection<T> oldList, Function<T, String> hashFunc) {
        Map<String, T> newMap = toMap(newList, hashFunc);
        Map<String, T> oldMap = toMap(oldList, hashFunc);

        List<T> needAddList = new ArrayList<>();
        List<T> noChangeList = new ArrayList<>();

        for (Map.Entry<?, T> entry : newMap.entrySet()) {
            if (oldMap.containsKey(entry.getKey())) {
                noChangeList.add(entry.getValue());
            } else {
                needAddList.add(entry.getValue());
            }
        }

        List<T> needDeleteList = oldMap.entrySet()
                .stream()
                .filter(entry -> !newMap.containsKey(entry.getKey()))
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

        return new CollectionDiffResult<>(needAddList, needDeleteList, noChangeList);
    }
}
